package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Reference
    private ITravelService travelService;


    public void save(TravelComment comment) {
        comment.setCreateTime(new Date());
        repository.save(comment);
    }

    public Page query(TravelCommentQuery qo) {
        Query query = new Query();
        if (qo.getTravelId() != -1) {
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        //total
        long total = template.count(query, TravelComment.class);


        query.with(pageable);
        //list
        List<TravelComment> list = template.find(query, TravelComment.class);
        List commentList = new ArrayList();
        for (TravelComment comment : list) {
            commentList.add(0,comment);
        }
        return new PageImpl(commentList, pageable, total);
    }

    public TravelComment commentAdd(TravelComment comment) {
        comment.setCreateTime(new Date());
        //如果是评论的评论
        if (comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE){
            String refId = comment.getRefComment().getId();
            if (StringUtils.hasLength(refId)){
                TravelComment refComment = repository.findById(refId).get();
                if (refComment !=null){
                    comment.setRefComment(refComment);
                }
            }
        }
        repository.save(comment);
        return comment;
    }

    public long getCount(Long travelId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        //total
        long total = template.count(query, TravelComment.class);

        return total;
    }

}
